from flask import Blueprint,request,json,jsonify
from application.models.users.user import *
user_blue = Blueprint("userblue",__name__)

@user_blue.route('/addpictype',methods=['POST'])
def add():
    data = json.loads(request.data)
    name = data['name']
    uid = data['uid']
    tt = Pictype(name=name,uid=uid)
    db.session.add(tt)
    db.session.commit()
    return jsonify({'code':200,'mes':"添加相册成功"})


@user_blue.route('/updatepictype',methods=['PUT'])
def put():
    data = json.loads(request.data)
    id = data['id']
    Pictype.query.filter(Pictype.id==id).update({
        'id':data['id'],
        'name':data['name'],
        'uid':data['uid']
    })
    db.session.commit()
    return jsonify({
        'code':200,
        'mes':"修改相册成功"
    })

@user_blue.route('/deletepictype',methods=['DELETE'])
def delp():
    id = request.args.get('id')
    Pictype.query.filter(Pictype.id == id).delete()
    db.session.commit()
    return jsonify({'code':200,'mes':"删除相册成功"})

@user_blue.route('/getallpictype')
def getall():
    type_list = Pictype.query.all()
    pylist = [{
        'id':i.id,
        'name':i.name,
        'uid':i.uid
    }for i in type_list]
    return jsonify({'code':200,'pylist':pylist})


@user_blue.route('/addpic',methods=['POST'])
def pic():
    data = json.loads(request.data)
    name = data['name']
    url = data['url']
    picid = data['picid']
    uid = data['uid']
    pic = Pic(name=name,url=url,picid=picid,uid=uid)
    db.session.add(pic)
    db.session.commit()
    return jsonify({'code':200,'mes':"添加照片成功"})

import os
@user_blue.route('/upload',methods=['POST'])
def upload():
    file = request.files.get('file')
    filename = file.filename
    path = os.path.join("static/upload/" + filename)
    file.save(path)
    return jsonify({'code':200,'url':path})

@user_blue.route('/getpic')
def getpic():
    pid = request.args.get('id')
    pic = Pic.query.filter(Pic.picid==pid)
    plist = [{
        'id':i.id,
        'name':i.name,
        'url':i.url
    }for i in pic]
    return jsonify({
        'code':200,
        'piclist':plist
    })


@user_blue.route('/deletepic',methods=['DELETE'])
def delpic():
    pid = request.args.get('id')
    Pic.query.filter(Pic.id == pid).delete()
    db.session.commit()
    return jsonify({'code':200,'mes':"删除照片成功"})


